import { onMounted, onUnmounted, ref } from 'vue'

export default function(props, collapseContainer, resizeBar) {
  const width = ref<number>(props.minWidth);
  const maxWidth = ref<number>(0);
  const minExistWidth = ref<number>(5);
  const maxHeight = ref<number>(0);
  const mutationObserver = ref();
  onMounted(() => {
    maxWidth.value = collapseContainer.value.offsetWidth;
    maxHeight.value = collapseContainer.value.offsetHeight;
    const observerOptions = {
      childList: false, // 观察目标子节点的变化，是否有添加或者删除
      attributes: true, // 观察属性变动
      subtree: false // 观察后代节点，默认为 false
    };
    mutationObserver.value = new MutationObserver((entries) => {
      // 当DOM元素的宽高发生变化时执行回调函数
      methods.handleResize(entries[0].target);
    });
    mutationObserver.value.observe(resizeBar.value, observerOptions);
  })
  onUnmounted(() => {
    mutationObserver.value.disconnect();
  })
  const methods = {
    /**
     * 监听dom大小改变
     * @param {*} dom
     */
    handleResize(dom) {
      width.value = dom.offsetWidth;
    },
    /**
     * 主动折叠/收缩
     * 1 => 展开左侧, 0 => 恢复默认, -1 => 收缩左侧
     * @param {*} direction
     */
    collapse(direction) {
      switch (direction) {
        case 1:
          width.value = maxWidth.value - minExistWidth.value;
          break;
        case -1:
          width.value = minExistWidth.value;
          break;
        case 0:
        default:
          width.value = props.minWidth;
          break;
      }
    }
  }
  return {
    methods,
    width,
    maxWidth,
    maxHeight,
    minExistWidth
  }
}
